<template>
  <div class="login">
    <h1>HELLO!</h1>
    <br>
    <h3>欢迎来到Admin Better!</h3>
    <br>
    <el-form
      ref="ruleFormRef"
      style="max-width: 400px"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="50"
      class="demo-ruleForm"
    >
      <el-form-item label="账号" prop="username">
        <el-input v-model="ruleForm.username" type="username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button style="width: 100%;border-radius: 20px;" type="primary" @click="submitForm"> 登录 </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
import type { FormRules } from 'element-plus'
import axios from 'axios'

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入账号'))
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  }
}

const ruleForm = reactive({
  username: '',
  password: ''
})

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ validator: validatePass, trigger: 'blur' }],
  password: [{ validator: validatePass2, trigger: 'blur' }]
})

const submitForm = async () => {
  await axios.post('/api/login', ruleForm).then((res) => {
    console.log(res.data)
    const { data, code, token, message } = res.data
    if (code === 10000) {
      alert(message)
      localStorage.setItem('token', res.data.data.accessToken)
      localStorage.setItem('avator', res.data.data.userInfo.avator)
      localStorage.setItem('nickname', res.data.data.userInfo.nickname)
      window.location.href = '/'
    } else {
      alert(message)
    }
  })
}
</script>

<style scoped>
.login{
    width: 400px;
    height: 250px;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    background: rgb(256, 256, 256,.5);
}
</style>